#coding:utf-8
import os
import time
from django.http import HttpResponse
from django.shortcuts import render
from models import WebUsers
from django.views.decorators.http import require_http_methods
from tools.forms import WebLonginForm
from tools.forms import UploadFileForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

# Create your views here.
def showLogin(request):
    if request.session.get('login'):
        return render(request, 'index.html')
    return render(request, 'login.html')
#登入验证
@require_http_methods("POST")
def webLogin(request):
    form = WebLonginForm(request.POST)  # form 包含提交的数据
    if form.is_valid():  # 如果提交的数据合法
        name = form.cleaned_data['name']
        password = form.cleaned_data['password']
        webadmin=WebUsers.objects.get(name=name)
        if webadmin.password==password:
            request.session['login']='login'
            return render(request, 'index.html')
    else:
        return render(request, 'login.html')

def logut(request):
    if request.session.get('login'):
        del request.session['login']  # 删除session
    return render(request, 'login.html')

def upload_file(request):
  if request.method == 'POST':
     form = UploadFileForm(request.POST, request.FILES)
     if form.is_valid():
        handle_uploaded_file(request.FILES['file'])
        return HttpResponseRedirect('/success/url')
  else:
     form = UploadFileForm()
  return render_to_response('upload.html', {'form': form})

def handle_uploaded_file(f):
    file_name = ""
    try:
        path = "./media/image" + time.strftime('/%Y/%m/%d/%H/%M/%S/')
        if not os.path.exists(path):
            os.makedirs(path)
            file_name = path + f.name
            destination = open(file_name, 'wb+')
            for chunk in f.chunks():
                destination.write(chunk)
            destination.close()
    except Exception, e:
        print e

    return file_name